package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿管理
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     * 两种获得id的方式 session threadLocal
     */
    @PostMapping
    public R addressBook(@RequestBody AddressBook addressBook){

        //前端没传userId 需要自己设置userId 通过threadLocal获得
        addressBook.setUserId(BaseContext.getCurrentId());

        //调用save方法保存地址信息
        addressBookService.save(addressBook);

        //返回成功信息
        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * return addressBook
     */
    @PutMapping("/default")
    public R<AddressBook> getDefaultAddress(@RequestBody AddressBook addressBook){
        //将当前用户所有地址的is_defalut字段的值设为0
        LambdaUpdateWrapper<AddressBook> addressBookLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        addressBookLambdaUpdateWrapper.set(AddressBook::getIsDefault,0);
        addressBookLambdaUpdateWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        addressBookService.update(addressBookLambdaUpdateWrapper);

        //将当前地址设为默认地址 is_defalut字段设为1
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
//        LambdaUpdateWrapper<AddressBook> addressBookqw = new LambdaUpdateWrapper<>();
//        addressBookqw.set(AddressBook::getIsDefault,1);
//        addressBookqw.eq(AddressBook::getId,addressBook.getId());
//        addressBookService.update(addressBookqw);

        //返回信息
//        return R.success("设置成功");
        return R.success(addressBook);
    }


    /**
     * 根据id查询地址  id是addressBook表中的主键
     * @param id
     * return R
     */
    @GetMapping("/{id}")
    public R getAddressById(@PathVariable Long id){
//        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        addressBookLambdaQueryWrapper.eq(AddressBook::getId,id);
//        AddressBook addressBook= addressBookService.getById(addressBookLambdaQueryWrapper);
        AddressBook addressBook= addressBookService.getById(id);
        return addressBook != null?R.success(addressBook):R.error("没有找到该对象");
    }

    /**
     * 根据用户id查询默认地址
     * @param
     *
     */
    @GetMapping("/default")
    public R<AddressBook> getDefaultAddressByUserId(){
        //根据userID和is_default字段查询
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());

        AddressBook defaultAddress = addressBookService.getOne(addressBookLambdaQueryWrapper);
        return defaultAddress != null?R.success(defaultAddress):R.error("没有找到该对象");
    }

    /**
     * 根据用户id查询指定用户的全部地址
     *
     */
    @GetMapping("/list")
    public R getAllAddressByUserId(AddressBook addressBook){
//        //根据userId字段查询全部地址
//        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
//        AddressBook allAddress = addressBookService.getById(addressBookLambdaQueryWrapper);
//        return R.success(allAddress);

            addressBook.setUserId(BaseContext.getCurrentId());
            log.info("addressBook:{}", addressBook);

            //条件构造器
            LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
            queryWrapper.orderByDesc(AddressBook::getUpdateTime);

            //SQL:select * from address_book where user_id = ? order by update_time desc
            return R.success(addressBookService.list(queryWrapper));

    }

    /**
     * 删除地址  //可能是多个
     */
    @DeleteMapping
    public R deleteByIds(@RequestParam List<Long> ids){
        boolean flag = addressBookService.removeByIds(ids);
        return flag?R.success("删除成功"):R.error("删除失败");
    }

    /**
     * 修改地址
     * @param
     */
    @PutMapping
    public R updateAddress(  AddressBook addressBook){
//        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        addressBookLambdaQueryWrapper.eq(AddressBook::getId,addressBook);
        boolean b = addressBookService.updateById(addressBook);
        return b?R.success("修改成功"):R.error("修改失败");
    }
}

